const UserModel = require("../models/user");
const axios = require("axios");
const jsonwebtoken = require("jsonwebtoken");
class UserController {
  // 检查用户是否存在
  async checkUserExist(ctx) {
    try {
      const result = await UserModel.findById({ username: ctx.params.userId });
      console.log(result, "用户是否存在");
      ctx.body = {
        errno: 0,
        message: "该用户已存在，请勿重复添加",
        data: result,
      };
    } catch (error) {
      console.log(error, "error");
    }
  }

  // 创建用户
  async createUser(ctx) {
    const user = ctx.request.body;
    try {
      const result = await UserModel.find({ username: user.username });
      if (result.length > 0) {
        return (ctx.body = {
          errno: 0,
          message: "用户名重复，换一个试试吧",
        });
      }
      const newUser = new UserModel({ ...user });
      await newUser.save();
      ctx.body = {
        errno: 0,
        message: "创建成功",
      };
    } catch (error) {
      ctx.body = {
        errno: 0,
        message: "操作失败",
      };
    }
    ctx.body = {
      errno: 0,
      message: "创建成功",
    };
  }

  // 获取所有的用户
  async listUsers(ctx) {
    console.log(ctx.state.user, "命名空间的内容");
    // 在此处校验token
    let { page = 1, pageSize = 20 } = ctx.query;
    page = Number(page);
    pageSize = Number(pageSize);
    try {
      // _id: { $lt: "620f9b2322bf31c0e7309252" },
      const result = await UserModel.find({
        _id: { $gt: "620f9b2322bf31c0e7309252" },
      })
        .skip((page - 1) * pageSize)
        .limit(pageSize);
      ctx.body = {
        errno: 0,
        message: "操作成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        errno: 1,
        message: "操作失败",
      };
    }
  }

  //   用户登录
  login(ctx) {
    console.log(process.env.tokenSecret, "登录的密钥");
    // expiresIn:过期时间
    const token = jsonwebtoken.sign(
      { username: ctx.request.body.username },
      process.env.tokenSecret,
      { expiresIn: "3d" }
    );
    ctx.body = {
      errno: 0,
      message: "登录成功",
      token,
    };
  }

  // 检查是否是拥有操作权限
  checkOwner(ctx) {}

  // 将IP地址解析为地理位置
  async resolveIp(ctx) {
    const ip = "101.82.203.42";
    const mapKey = "9994ea2619c5610863aa62a8e0dca06b";
    const result = await axios.get(
      `https://restapi.amap.com/v3/ip?ip=${ip}&key=${mapKey}`
    );
    ctx.body = {
      errno: 0,
      message: "地理位置解析成功",
      data: result.data,
    };
  }
}

module.exports = new UserController();
